{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d60dc36e-b5c2-4904-8924-3ed1bb1ffe12",
   "metadata": {},
   "outputs": [],
   "source": [
    "from openai import OpenAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2170c7a6-057a-4344-b749-232715218d5d",
   "metadata": {},
   "outputs": [],
   "source": [
    "client = OpenAI()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "302ba225-1251-4356-a11b-f56bc9f53062",
   "metadata": {},
   "outputs": [],
   "source": [
    "assistant = client.beta.assistants.create(\n",
    "    model=\"gpt-3.5-turbo\",\n",
    "    name=\"数学助手\",\n",
    "    instructions=\"你是一个数学助手，可以通过编写和运行代码来回答数学相关问题。\",\n",
    "    tools=[{\"type\": \"code_interpreter\"}]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5d21f5c5-50b3-41aa-878b-34e8fbfec9b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "thread = client.beta.threads.create()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "36d66a0f-ad53-4502-8f71-577ee79cca67",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'thread_qjyG7TTbIDpvcNQAdFO9KiMj'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "thread.id"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f8d7af0d-0c74-4323-bb08-1669d8f2ef74",
   "metadata": {},
   "outputs": [],
   "source": [
    "message = client.beta.threads.messages.create(\n",
    "    thread_id=thread.id,\n",
    "    role=\"user\",\n",
    "    content=\"我需要解这个方程`5x^2−1200x+72000=0，未知数应该是多少？\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "01599e9c-f320-4cc0-8e3c-8191879bbf07",
   "metadata": {},
   "outputs": [],
   "source": [
    "run = client.beta.threads.runs.create(\n",
    "    thread_id=thread.id,\n",
    "    assistant_id=assistant.id,\n",
    "    instructions=\"请称呼用户为粒粒\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "0ca9959d-fc01-4233-9fc8-5efb0ae331f7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Run(id='run_UqgpuliqyeJG7ro1VCaB2hBS', assistant_id='asst_jtLgtWj5ee3K4PyzGf3i4MJD', cancelled_at=None, completed_at=None, created_at=1713238485, expires_at=1713239085, failed_at=None, file_ids=[], instructions='请称呼用户为粒粒', last_error=None, metadata={}, model='gpt-3.5-turbo', object='thread.run', required_action=None, started_at=None, status='queued', thread_id='thread_qjyG7TTbIDpvcNQAdFO9KiMj', tools=[CodeInterpreterTool(type='code_interpreter')], usage=None, temperature=1.0, top_p=1.0, max_completion_tokens=None, max_prompt_tokens=None, truncation_strategy={'type': 'auto', 'last_messages': None}, incomplete_details=None, response_format='auto', tool_choice='auto')"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "dee20b75-da34-49b9-a2c6-419b6d0db9ad",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'completed'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.beta.threads.runs.retrieve(\n",
    "    thread_id=thread.id,\n",
    "    run_id=run.id\n",
    ").status"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "ee9c8c21-25c8-4adb-b1b8-233965650e9a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "运行状态：completed\n"
     ]
    }
   ],
   "source": [
    "while run.status != \"completed\":\n",
    "    keep_retrieving_run = client.beta.threads.runs.retrieve(\n",
    "        thread_id=thread.id,\n",
    "        run_id=run.id\n",
    "    )\n",
    "    print(f\"运行状态：{keep_retrieving_run.status}\")\n",
    "    if keep_retrieving_run.status == \"completed\":\n",
    "        break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "128c4e88-eb8d-4b8c-b225-c6b775cdae0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "messages = client.beta.threads.messages.list(\n",
    "    thread_id=thread.id\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "14c3b05f-af8f-4374-81dd-81035cdcacc7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[Message(id='msg_CATnOIPcyBdnTwUDnzoS6P94', assistant_id='asst_jtLgtWj5ee3K4PyzGf3i4MJD', completed_at=None, content=[TextContentBlock(text=Text(annotations=[], value='经过计算，方程5x^2−1200x+72000=0的根是x=120。因此，未知数x的值为120。如果你有任何其他问题或需要进一步帮助，请随时告诉我。'), type='text')], created_at=1713238498, file_ids=[], incomplete_at=None, incomplete_details=None, metadata={}, object='thread.message', role='assistant', run_id='run_UqgpuliqyeJG7ro1VCaB2hBS', status=None, thread_id='thread_qjyG7TTbIDpvcNQAdFO9KiMj'),\n",
       " Message(id='msg_5u0uAHuR9NDRUjKznfxZoyz7', assistant_id='asst_jtLgtWj5ee3K4PyzGf3i4MJD', completed_at=None, content=[TextContentBlock(text=Text(annotations=[], value='你想要解这个二次方程来找出未知数x的值是吧。我可以帮你用求根公式来找到方程的根。让我们开始计算吧。'), type='text')], created_at=1713238486, file_ids=[], incomplete_at=None, incomplete_details=None, metadata={}, object='thread.message', role='assistant', run_id='run_UqgpuliqyeJG7ro1VCaB2hBS', status=None, thread_id='thread_qjyG7TTbIDpvcNQAdFO9KiMj'),\n",
       " Message(id='msg_i3D0A5qqm3ORY6NxAZbGRaXg', assistant_id=None, completed_at=None, content=[TextContentBlock(text=Text(annotations=[], value='我需要解这个方程`5x^2−1200x+72000=0，未知数应该是多少？'), type='text')], created_at=1713238404, file_ids=[], incomplete_at=None, incomplete_details=None, metadata={}, object='thread.message', role='user', run_id=None, status=None, thread_id='thread_qjyG7TTbIDpvcNQAdFO9KiMj')]"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "messages.data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "f724b18f-d37d-45b7-a165-f38b71173883",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "经过计算，方程5x^2−1200x+72000=0的根是x=120。因此，未知数x的值为120。如果你有任何其他问题或需要进一步帮助，请随时告诉我。\n",
      "------\n",
      "你想要解这个二次方程来找出未知数x的值是吧。我可以帮你用求根公式来找到方程的根。让我们开始计算吧。\n",
      "------\n",
      "我需要解这个方程`5x^2−1200x+72000=0，未知数应该是多少？\n",
      "------\n"
     ]
    }
   ],
   "source": [
    "for data in messages.data:\n",
    "    print(data.content[0].text.value)\n",
    "    print(\"------\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "0e82c184-9c5b-4768-8904-1c7e83248803",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_response_from_assistant(assistant, thread, prompt, run_instruction=\"\"):\n",
    "    message = client.beta.threads.messages.create(\n",
    "    thread_id=thread.id,\n",
    "    role=\"user\",\n",
    "    content=prompt\n",
    "    )\n",
    "    \n",
    "    run = client.beta.threads.runs.create(\n",
    "      thread_id=thread.id,\n",
    "      assistant_id=assistant.id,\n",
    "      instructions=run_instruction\n",
    "    )\n",
    "    \n",
    "    while run.status != \"completed\":\n",
    "        keep_retrieving_run = client.beta.threads.runs.retrieve(\n",
    "            thread_id=thread.id,\n",
    "            run_id=run.id\n",
    "        )\n",
    "        print(f\"Run status: {keep_retrieving_run.status}\")\n",
    "\n",
    "        if keep_retrieving_run.status == \"completed\":\n",
    "            break\n",
    "    \n",
    "    messages = client.beta.threads.messages.list(\n",
    "        thread_id=thread.id\n",
    "    )\n",
    "    \n",
    "    for data in messages.data:\n",
    "        print(\"\\n\")\n",
    "        print(data.content[0].text.value)\n",
    "        print(\"------\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "cebc1056-d011-46d3-b144-a538618cad41",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Run status: in_progress\n",
      "Run status: in_progress\n",
      "Run status: in_progress\n",
      "Run status: in_progress\n",
      "Run status: in_progress\n",
      "Run status: in_progress\n",
      "Run status: in_progress\n",
      "Run status: in_progress\n",
      "Run status: completed\n",
      "\n",
      "\n",
      "2的56次方等于72057594037927936。如果你有任何其他问题，欢迎随时向我提问。\n",
      "------\n",
      "\n",
      "\n",
      "要计算2的56次方，只需要将2乘以自身共56次。让我们计算一下。\n",
      "------\n",
      "\n",
      "\n",
      "2的56次方等于多少\n",
      "------\n",
      "\n",
      "\n",
      "经过计算，方程5x^2−1200x+72000=0的根是x=120。因此，未知数x的值为120。如果你有任何其他问题或需要进一步帮助，请随时告诉我。\n",
      "------\n",
      "\n",
      "\n",
      "你想要解这个二次方程来找出未知数x的值是吧。我可以帮你用求根公式来找到方程的根。让我们开始计算吧。\n",
      "------\n",
      "\n",
      "\n",
      "我需要解这个方程`5x^2−1200x+72000=0，未知数应该是多少？\n",
      "------\n"
     ]
    }
   ],
   "source": [
    "get_response_from_assistant(assistant, thread, \"2的56次方等于多少\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "655eb3f1-b4da-4684-a050-5a869ad66685",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
